<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController
{
	/**
	 * @var array the breadcrumbs of the current page. The value of this property will
	 * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
	 * for more details on how to specify this property.
	 */
	public $breadcrumbs=array();

    public function AssignData(&$ref,$class) {
        $i=0;
        foreach($_POST[$class] as $item) {
            $ref[$i] = new $class;
            $ref[$i]->attributes = $item;
            $i++;
        }
    }
    public function makeSubmitScript() {
        $r = CHtml::normalizeUrl('');
        $cs = Yii::app()->getClientScript();
        $ScriptPos = (Yii::app()->request->isAjaxRequest)?CClientScript::POS_END:CClientScript::POS_READY;
        $s =<<<EOD
$("form[action='$r'] input[type='submit']").bind({
                                                  'click':  function(){
                                                                $.simplelogform.Submit($('form[action="$r"]'));
                                                                return false;
                                                            }
                                                });
EOD;
        $cs->registerScript(__CLASS__.'#submitButton',$s,$ScriptPos);
        if(!Yii::app()->request->isAjaxRequest)
        	$cs->registerScriptFile('/javascript/ajaxloading.js');
    }
    public function AjaxRender($view,$data=null) {
        $output = preg_replace("/[\n\r]/",' ',$this->renderPartial($view, $data, true, true));
        echo "$(\"#content\").append($('<div/>').html(\"$output\"));";
    }
    public function setReferrer($key) {
        if(isset($_POST['ref']))
            $r = $_POST['ref'];
        elseif(isset($_GET['ref']))
            $r = $_GET['ref'];
        if(!empty($r)) {
            $s = Yii::app()->getSession();
            $s->open();
            $s[$key]=array('ref'=>$r);
            $s->close();
        }
    }
    public function getReferrer($key) {
        $s = Yii::app()->getSession();
        $s->open();
        $r = $s[$key];
        return $r['ref'];
    }
    public function BreadCrumbs($ref,$clean=false) {
        $s=Yii::app()->getSession();
        $s->open();
        $crumbs = $s['breadcrumbs'];
        if(!$clean && empty($crumbs))
            $crumbs = array_merge($crumbs,$ref);
        else
            $crumbs = $ref;//array_unshift($ref,array('Home'=>array('site/index')));
        if(end($ref)!==end($crumbs)) {
            $key = array_search(end($ref),$crumbs);
            $found = false;
            $_crumbs = array();
            foreach($crumbs as $k=>$v) {
                if($k == $key)
                    $found = true;
                if($found)
                    $_crumbs[$k]=$v;
            }
            $crumbs = $_crumbs;
        }
        elseif(count($crumbs)>3) {
            $_c = array_reverse($crumbs);
            $lastVisit = $_c[1];
        }
        else
            $lastVisit = null;
        $this->breadcrumbs = $crumbs;
        $s['breadcrumbs'] = $crumbs;
        $s->close();
        return $lastVisit;
    }
    public function forAjax() {
        
    }
    public function makeErrorByName($item = array(),$css='error') {
        $js='';
        foreach($item as &$_item) {
            $_item = "form input[name='$_item']";
        }
        $selector = implode(',',$item);
        if($selector!='')
            $js.="$(\"$selector\").addClass('$css');";
        return $js;
    }
    public function makeErrorByValue($item = array(),$css='error') {
        $g=0;
        $condition = '';
        $js='';
        foreach($item as $_item) {
           if($g>0)
                    $condition .= ' || ';
                $condition .= 'yval=="'.$_item.'"';
            $g++;
        }
        if($condition!='') {
            $js = "$('form input').each(function(){var yval = $(this).val(); if($condition){ $(this).addClass('$css');} });";;
        }
        return $js;
    }
    public function makeErrorMsg($error = array(),$header=null,$footer=null,$htmlOptions=array()) {
        $content='';
        foreach($error as $err) {
            if($err!='')
                $content.="<li>$err</li>";
        }
        if($content!=='') {
            if($header===null)
                $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
            if(!isset($htmlOptions['class']))
                $htmlOptions['class']=CHtml::$errorSummaryCss;
            return CHtml::tag('div',$htmlOptions,$header."<ul>$content</ul>".$footer);
        }
        else
            return '';
    }
    public function makeJsErrorMsg($error,$container='errorsummary') {
        return ($error!='')?"$('#$container').html('$error');":'';
    }
    private function encodeSelector($str){
        $ary = array('#'=>'\\#',';'=>'\\;','&'=>'\\&',','=>'\\,','.'=>'\\.','+'=>'\\+','*'=>'\\*','~'=>'\\~',':'=>'\\:','"'=>'\\"','!'=>'\\!','^'=>'\\^','$'=>'\\$','['=>'\\[',']'=>'\\]','('=>'\\(',')'=>'\\)','='=>'\\=','>'=>'\\>','|'=>'\\|','/'=>'\\/',"'"=>"\\'");
        return strtr($str,$ary);
    }
    public function getErrorName($model,$header=null,$footer=null,$htmlOptions=array()){
        $errorAttri = array();
        $errorSummary = array();
        $returnVal ='';
        if(!is_array($model))
            $model = array($model);
        foreach($model as $m) {
            if($m instanceof CActiveRecord) {
                foreach($m->getErrors() as  $name=>$err) {
                    $errorAttri[]=CHtml::resolveName($m, $name);
                    $errorSummary[]=$err[0];
                }
            }
            elseif(is_array($m) && $m[0] instanceof CActiveRecord) {
                foreach($m as $i=>$_m) {
                    $err1 = array();
                    foreach($_m->getErrors() as $n=>$e) {
                        $_n = "[$i]".$n;
                        $errorAttri[] =CHtml::resolveName($_m, $_n);
                        if(!in_array($e[0],$errorSummary))
                            $errorSummary[] = $e[0];
                    }
                }
            }
        }
        return array('attr'=>$errorAttri,'summary'=>$this->makeErrorMsg($errorSummary,$header=null,$footer=null,$htmlOptions=array()));
    }
    public function makeModelError($model,$header=null,$footer=null,$htmlOptions=array()) {
        $r = $this->getErrorName($model,$header=null,$footer=null,$htmlOptions=array());
        $returnVal = $this->makeErrorByName($r['attr']);
        $returnVal .= $this->makeJsErrorMsg($r['summary']);
        return $returnVal;
    }

    public function saveMore2More($ref) {
        $ID = null;
        foreach($this->$ref as $item) {
            if($item->$ref != 0 && !empty($item->$ref) && $item->$ref != '')
            {
                $_id = $item->save();
                if($_id===false) {
                    return false;
                }
                if($_id != 0)
                    $ID[] = $_id;
            }
        }
        $db = $this->dbConnection;
        $criteria = new CDbCriteria;
        $criteria->condition = 'cargo_id = :cargo_id';
        $criteria->params = array(':cargo_id'=>$this->id);
        if(!$this->isNewRecord) {
            if($db->commandBuilder->createDeleteCommand("cargo_join_".$ref,$criteria)->execute() === null){
                return false;
            }
        }
        foreach($ID as $item) {
            $db->commandBuilder->createInsertCommand("cargo_join_".$ref,array('cargo_id'=>$this->id,$ref."_id"=>$item))->execute();
        }
        return true;
    }
}